<template>
  <div>
    <a-modal
      :visible.sync="visible"
      v-bind="$attrs"
      v-on="$listeners"
      :maskClosable="false"
      :footer="null"
      width="700px"
      :title="model.text"
      wrapClassName="add-modal-container"
      @cancel="closeModal()"
    >
      <div class="curve-modal-body">
        <a-form-model ref="ruleForm" :model="form" :rules="rules">
          <a-row :gutter="0">
            <a-col :span="24">
              <a-form-model-item
                ref="tenantCode"
                label="所属项目"
                prop="tenantCode"
              >
                <a-select
                  show-search
                  allowClear
                  placeholder="请选择所属项目"
                  :loading="project.loading"
                  :filter-option="filterOption"
                  v-model="form.tenantCode"
                  @change="handleProjectChange($event)"
                >
                  <a-select-option
                    :value="item.proCode"
                    v-for="(item, index) in project.source"
                    :key="index"
                  >
                    {{ item.proName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="24">
              <a-form-model-item ref="pid" label="上级单位" prop="pid">
                <depart-popup
                  :disabled="!form.tenantCode"
                  placeholder="请选择上级单位"
                  :url="
                    `/mdata/organization/getTreeSysOrganizationByProCode?proCode=${form.tenantCode}`
                  "
                  v-model="form.pid"
                ></depart-popup>
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- <a-row :gutter="0">
            <a-col :span="24">

              <a-form-model-item label="归属公司">
                <a-select
                  v-model="form.companyCode"
                  placeholder="请选择归属公司"
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="(item, index) in companySource"
                    :key="index"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row> -->

          <a-row :gutter="0">
            <a-col :span="24">
              <a-form-model-item label="单位名称" prop="orgName">
                <a-input
                  placeholder="请输入单位名称"
                  v-model="form.orgName"
                ></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <!-- 组织编码   （编辑页面时此字段不可编辑） -->
            <!-- <a-col :span="12">
              <a-form-model-item ref="orgCode" label="组织编码" prop="orgCode">
                <a-input
                  v-model.trim="form.orgCode"
                  placeholder="请输入组织编码"
                  :maxLength="100"
                  :disabled="model.id ? true : false"
                />
              </a-form-model-item>
            </a-col> -->
            <a-col :span="24">
              <!-- 组织名称 -->
              <!-- <a-form-model-item ref="orgName" label="组织名称" prop="orgName">
                <a-input
                  v-model.trim="form.orgName"
                  placeholder="请输入组织名称"
                  :maxLength="255"
                />
              </a-form-model-item> -->
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="12">
              <!-- 类型 -->
              <a-form-model-item
                ref="secTypeValue"
                label="类型"
                prop="secTypeValue"
              >
                <a-select
                  v-model="form.secTypeValue"
                  placeholder="请选择类型"
                  :loading="secTypeLoading"
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="(item, index) in secTypeSource"
                    :key="index"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 排序 -->
            <a-col :span="12">
              <a-form-model-item ref="sort" label="排序" prop="sort">
                <a-input
                  v-model="form.sort"
                  type="number"
                  placeholder="请输入排序"
                  :maxLength="11"
                />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="0">
            <a-col :span="12">
              <a-form-model-item label="联系人">
                <a-input
                  v-model.trim="form.orgPerson"
                  placeholder="请输入联系人"
                  :maxLength="250"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="联系方式">
                <a-input
                  v-model.trim="form.orgTelephone"
                  placeholder="请输入联系方式"
                  :maxLength="255"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="0" v-if="false">
            <a-col :span="24">
              <!-- 路线坐标 -->
              <a-form-model-item ref="routeCoordinates" label="路线坐标">
                <a-input
                  v-model="form.routeCoordinates"
                  disabled
                  placeholder="请绘制线路坐标"
                  type="textarea"
                  style="height: 100px"
                />
                <div class="map-container">
                  <div id="organization-map"></div>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div class="curve-modal-footer">
        <a-button type="default" @click="closeModal()">取消 </a-button>
        <a-button type="primary" :loading="loading" @click="onSubmit()">
          确定
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
//新增标段弹窗
import { axios } from "@/utils/request";
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  securityJsCode: "ecfcb87ee130b34b5f0d25862f5ef080",
};
import DepartPopup from "@/components/TopVUI/custom/DepartPopup";
import { TImageUpload } from "@/components";
let mapInstance = null;
export default {
  components: {
    DepartPopup,
    TImageUpload,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    model: {
      type: Object,
      default: {},
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getProjectList();
          this.getSecTypeList();
          this.getCompanyData();
          //   初始化地图;
          this.$nextTick(() => {
            if (this.model.text != "编辑") {
              //   this.initMap();
            } else {
              this.getDetail();
            }
          });
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      //项目
      project: {
        source: [],
        pro_code: undefined,
        loading: false,
      },
      loading: false,
      form: {
        //上级单位
        pid: "",
        //组织编码
        orgCode: "",
        //归属公司
        companyCode: undefined,
        //标段名称
        orgName: "",
        //排序
        sort: "",
        //类型
        secTypeValue: undefined,
        //所属项目
        tenantCode: undefined,
        //线路坐标
        routeCoordinates: "",
        orgPerson: "",
        orgTelephone: "",
      },
      rules: {
        pid: [{ required: true, message: "请选择上级单位", trigger: "change" }],
        orgCode: [
          { required: true, message: "请输入组织编码", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_-]+$/,
            message: "只能输入英文字母，数字，下划线，中划线",
          },
        ],
        orgName: [
          { required: true, message: "请输入单位名称", trigger: "blur" },
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
        secTypeValue: [
          { required: true, message: "请选择类型", trigger: "change" },
        ],
        tenantCode: [
          { required: true, message: "请选择所属项目", trigger: "change" },
        ],
        routeCoordinates: [{ required: true, message: "请绘制线路坐标" }],
      },
      //类型
      secTypeSource: [],
      secTypeLoading: false,
      mapModule: null,
      //归属公司
      companySource: [],
    };
  },
  mounted() {},
  methods: {
    handleProjectChange() {
      let { form } = this;
      if (!form.tenantCode) {
        return;
      }
      let item = this.project.source.find((v) => v.proCode == form.tenantCode);
      this.form.pid = item.id;
    },

    //查询项目列表
    getProjectList() {
      return new Promise((resolve, reject) => {
        this.project.loading = true;
        this.$get("/mdata/sysProject/getProListByTenantCode")
          .then((res) => {
            this.project.source = res.data ?? [];
            resolve();
          })
          .catch((_) => {
            this.project.source = [];
            reject();
          })
          .finally((_) => {
            this.project.loading = false;
          });
      });
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },

    selectContainer(triggerNode) {
      return triggerNode.parentNode;
    },
    //详情
    getDetail() {
      let { sysOrgExtend } = this.model;

      this.form = {
        pid: sysOrgExtend.pid,
        //排序
        sort: sysOrgExtend.sort,
        //组织编码
        orgCode: sysOrgExtend.orgCode,
        //归属公司
        companyCode: sysOrgExtend.companyCode,
        //项目名称
        orgName: sysOrgExtend.orgName,
        //排序
        sort: sysOrgExtend.sort,
        //类型
        secTypeValue: sysOrgExtend?.secTypeValue ?? undefined,
        //所属项目
        tenantCode: sysOrgExtend.tenantCode,
        //线路坐标
        routeCoordinates: sysOrgExtend?.routeCoordinates ?? "",
        uuid: sysOrgExtend?.uuid,
        orgPerson: this.model.orgPerson,
        orgTelephone: this.model.orgTelephone,
      };
      //   let lineData = [];
      //   if (this.form.routeCoordinates) {
      //     lineData = JSON.parse(this.form.routeCoordinates);
      //   } else {
      //     lineData = [];
      //   }
      //   this.$nextTick(() => {
      //     this.initMap(lineData);
      //   });
    },

    //提交
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let { form } = this;
          let formJson = {
            orgType: "org_type.05",
            pid: form.pid,
            //组织编码
            orgCode: form.orgCode,
            // 归属公司
            companyCode: form.companyCode,
            //标段名称
            orgName: form.orgName,
            //排序
            sort: form.sort,
            //类型
            secTypeValue: form.secTypeValue ? form.secTypeValue : "",
            //所属项目
            tenantCode: form.tenantCode,
            //线路坐标
            routeCoordinates: form.routeCoordinates,
            orgPerson: form.orgPerson,
            orgTelephone: form.orgTelephone,
          };
          let url = "";
          //编辑
          if (form.uuid) {
            formJson.uuid = form.uuid;
            url = "/mdata/organization/updateOrg";
          }
          //新增
          else {
            url = "/mdata/organization/saveOrg";
          }
          axios
            .post(url, formJson, {
              headers: {
                "Content-Type": "application/json",
              },
            })
            .then((res) => {
              this.$message.success(
                res.message ? res.message : "操作成功",
                1.5
              );
              this.closeModal();
              this.$parent.getTableData();
            })
            .catch((_) => {})
            .finally((_) => {
              this.loading = false;
            });
        }
      });
    },

    //查询类型
    getSecTypeList() {
      this.secTypeLoading = true;
      this.$post("/system/dicSet/getDicItemByCode", {
        code: "secType",
      })
        .then((res) => {
          let { data } = res;
          this.secTypeSource = data ?? [];
        })
        .catch((_) => {
          this.secTypeSource = [];
        })
        .finally((_) => {
          this.secTypeLoading = false;
        });
    },

    //查询归属公司
    getCompanyData() {
      this.$post("/system/dicSet/getDicItemByCode", {
        code: "participatingUnits",
      })
        .then((res) => {
          this.companySource = res?.data ?? [];
        })
        .catch((_) => {
          this.companySource = [];
        });
    },

    //初始化地图
    initMap(eletricFenceData = []) {
      //地图中心点
      let center = Math.ceil(eletricFenceData.length / 2);
      AMapLoader.load({
        key: "4a9b32384ac2ef8437f61e2357874137", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.Scale",
          "AMap.ToolBar",
          "AMap.ControlBar",
          "AMap.MouseTool",
          "AMap.MapType",
          "AMap.HawkEye",
          "AMap.Geolocation",
          "AMap.PlaceSearch",
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.mapModule = AMap;
          mapInstance = new AMap.Map("organization-map", {
            zoom: 15, //初始化地图级别
            center: [
              eletricFenceData?.[center]?.[0] || 119.37094691782585,
              eletricFenceData?.[center]?.[1] || 34.74193028641671,
            ],
          });
          mapInstance.on("click", (e) => {});
          if (!this.model.id || eletricFenceData.length == 0) {
            this.drawLine();
            return;
          } else {
            this.editLine(eletricFenceData);
          }
        })
        .catch((e) => {});
    },

    //绘制折线
    drawLine() {
      let _this = this;
      _this.mapModule.plugin(["AMap.MouseTool"], async function(e) {
        var mouseTool = new _this.mapModule.MouseTool(mapInstance);
        mouseTool.polyline({
          fillColor: "#ff15ff",
          strokeOpacity: 1,
          fillOpacity: 0.2,
          strokeColor: "#ff15ff",
          strokeWeight: 2,
          strokeStyle: "solid",
          strokeDasharray: [5, 5],
        });
        _this.mapModule.Event.addListener(mouseTool, "draw", function(pt) {
          //添加事件
          var arr = pt.obj.getPath();
          let pathArr = [];
          for (var i = 0; i < arr.length; i++) {
            pathArr.push([arr[i].lng, arr[i].lat]);
          }
          _this.form.routeCoordinates = JSON.stringify(pathArr);
        });
      });
    },

    //编辑折线
    editLine(path = []) {
      let _this = this;
      var polyline1 = new _this.mapModule.Polyline({
        path: path,
        fillColor: "#ff15ff",
        strokeOpacity: 1,
        fillOpacity: 0.2,
        strokeColor: "#ff15ff",
        strokeWeight: 2,
        strokeStyle: "solid",
        strokeDasharray: [5, 5],
      });
      mapInstance.add(polyline1);
      mapInstance.setFitView();
      _this.mapModule.plugin(["AMap.PolylineEditor"], async function(e) {
        let polyEditor = new _this.mapModule.PolylineEditor(
          mapInstance,
          polyline1,
          {
            //编辑样式
            editOptions: {
              strokeColor: "#ff15ff",
              strokeWeight: 2,
              fillColor: "#ff15ff",
              fillOpacity: 0.2,
            },
          }
        );
        polyEditor.close();
        polyEditor.setTarget(polyline1);
        polyEditor.open();
        polyEditor.on("adjust", (ev) => {
          console.log(1);
          _this.getAllSpot(polyEditor);
        });
        polyEditor.on("addnode", (ev) => {
          console.log(2);
          _this.getAllSpot(polyEditor);
        });
        polyEditor.on("removenode", (ev) => {
          console.log(3);
          _this.getAllSpot(polyEditor);
        });
      });
    },

    //获取地图上所有标点
    getAllSpot(e) {
      var arr = e.getTarget().getPath();
      let pathArr = [];
      for (var i = 0; i < arr.length; i++) {
        pathArr.push([arr[i].lng, arr[i].lat]);
      }
      this.form.routeCoordinates = JSON.stringify(pathArr);
    },

    //关闭弹窗
    closeModal() {
      this.resetForm();
      mapInstance && mapInstance.destroy();
      this.$emit("update:visible", false);
    },

    //重置表单
    resetForm() {
      this.form = {
        //上级单位
        pid: "",
        //组织编码
        orgCode: "",
        //归属公司
        companyCode: undefined,
        //标段名称
        orgName: "",
        //排序
        sort: "",
        //类型
        secTypeValue: undefined,
        //所属项目
        tenantCode: undefined,
        //线路坐标
        routeCoordinates: "",
        orgPerson: "",
        orgTelephone: "",
      };
      this.$refs.ruleForm.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
@primary-color: @primary-color;
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .ant-modal-header {
    position: relative;
    .ant-modal-title {
      &::before {
        content: "";
        position: absolute;
        top: 18px;
        left: 10px;
        background-color: @primary-color;
        height: 17px;
        width: 5px;
      }
    }
  }

  .curve-modal-body {
    padding: 14px;
    max-height: 700px;
    overflow: auto;
  }
  .curve-modal-footer {
    padding: 10px 16px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #e8e8e8;
    border-radius: 0 0 4px 4px;
    button {
      &:last-child {
        margin-left: 20px;
      }
    }
  }
  .ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 102px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
    }
  }
  .map-container {
    width: 100%;
    height: 340px;
    position: relative;
    box-sizing: border-box;
    border: 2px solid #fff;
    border-radius: 4px;
    #organization-map {
      height: 100%;
      width: 100%;
    }
  }
}
</style>
